#include "OBJLoader.h"

void OBJLoader::load(const string& filename, vector<Vertex*>& vertices,
		vector<Triangle*>& triangles, vector<Material*>& materials)
{
	ifstream fin(filename.c_str());
	if ( !fin)
	{
		std::cout << "Error opening " << filename << " for input" << std::endl;
		return;
	}
	
	// create default-material
	materials.push_back(new Material(makecol(100, 100, 100), makecol(0, 255, 0), makecol(25, 25, 25), 20.));

	vector<SPoint> points;
	string s;
	// read vertices
	while (getline(fin, s) )
	{
		if (s[0] == 'c')
		{ // material-line
			int sr, dr, ar;
			float a;
			sscanf(s.c_str(), "c %d %d %d %f", &sr, &dr, &ar, &a);
			std::cout << "New material loaded!" << std::endl;
			materials.push_back(new Material(sr, dr, ar, a));
		}
		else if (s[0] == 'v')
		{ // vertex-line
			if (s[1] == 'n')
			{
				float x, y, z;
				sscanf(s.c_str(), "vn %f %f %f", &x, &y, &z);
				std::cout << "Vertex loaded with normal: " << x << " " << y << " " << z << std::endl;
				vertices.push_back(new Vertex(points[vertices.size()], Vector(x, y, z)));
			}
			else
			{
				float x, y, z;
				sscanf(s.c_str(), "v %f %f %f", &x, &y, &z);
				std::cout << "Point loaded: " << x << " " << y << " " << z << std::endl;
				points.push_back(SPoint(x, y, z));
			}
		}
		else if (s[0] == 'f')
		{ // face-line
			int v1, v2, v3;
			sscanf(s.c_str(), "f %i//%i %i//%i %i//%i", &v1, &v1, &v2, &v2, &v3, &v3);
			const Vertex* p[3] =
			{ vertices[v1 - 1], vertices[v2 - 1], vertices[v3 - 1] };
			std::cout << "Triangle loaded: " << p[0]->getPoint() << " " << p[1]->getPoint() << " " << p[2]->getPoint() << std::endl;
			Material* m = materials[materials.size() - 1];
			triangles.push_back(new Triangle(p, m));
		}
	}

	fin.close();
}
